package com.mimo.admin.shiro.config;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import com.mimo.admin.exception.MismatchPasswordException;
import com.mimo.admin.exception.UserIsNotExistException;

public class UserCredentialsMatcher implements CredentialsMatcher {

  @Value("${mimo.admin.username}")
  private String username;

  @Value("${mimo.admin.password}")
  private String password;

  @Override
  public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo info) {

    UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
    String tokenUsername = token.getUsername();

    String tokenPassword = String.valueOf(token.getPassword());

    if (!(StringUtils.hasText(tokenUsername))) {
      throw new UnknownAccountException();
    }

    // 查出是否有此用户
    if (!this.username.equals(tokenUsername)) {
      throw new UserIsNotExistException();
    }

    //如果密码不正确
    if (!tokenPassword.equals(password)) {
      throw new MismatchPasswordException();
    }
    return true;
  }
}
